<template>
    <div class="app">
        <div class="header">
            <el-button type="primary" :icon="Plus" size="large" @click="handleAddUser">添加用户</el-button>
            <el-input v-model="input" placeholder="请输入你想搜索的内容" size="large" style="width: 400px; margin-left: 50px" />
        </div>
        <div class="tables" >
            <el-table :data="state.tableData" border style="width: 100%">
                <el-table-column prop="username" label="用户名" />
                <el-table-column prop="nickname" label="昵称" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column prop="roles__title" label="角色" />
                <el-table-column  label="状态">
                    <template #default="scope">
                        <el-switch
                            v-model="scope.row.status"
                            class="ml-2"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            @change="handleStatus(scope.row)"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="last_login" label="最后登录" :formatter="timeFormatter" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="small" type="success" @click="handleEdit(scope.row)">修改</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        
        <!-- 添加用户对话框 -->
        <div>
             <el-dialog v-model="dialogFormVisible" title="添加用户">
                <el-form :model="state.form" class="forms" :rules="rules" ref="userRules">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="state.form.username" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="state.form.password" /> 
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="state.form.email" />
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname">
                        <el-input v-model="state.form.nickname" />
                    </el-form-item>
                    <el-form-item label="角色">
                        <el-select v-model="state.form.roleId" class="m-2" placeholder="请选择角色">
                            <el-option
                            v-for="item in state.role"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="个性签名" class="signa">
                        <el-input v-model="state.form.signatrue" type="textarea" />
                    </el-form-item>
                </el-form>
                <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleAdd">确定</el-button>
                </span>
                </template>
            </el-dialog>
        </div>

        <!-- 修改用户对话框 -->
        <div>
             <el-dialog v-model="dialogFormVisible2" title="修改用户">
                <el-form :model="state.editList" class="forms" :rules="rules2" ref="userRules2">
                    <el-form-item label="用户名">
                        <el-input v-model="state.editList.username" />
                    </el-form-item>
                    <el-form-item label="邮箱">
                        <el-input v-model="state.editList.email" />
                    </el-form-item>
                    <el-form-item label="角色分配">
                        <el-select v-model="state.editList.roles__title" class="m-2" placeholder="请选择角色">
                            <el-option
                            v-for="item in state.role"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="昵称">
                        <el-input v-model="state.editList.nickname" />
                    </el-form-item>
                    <el-form-item label="个性签名" class="signa">
                        <el-input v-model="state.editList.signature" type="textarea" />
                    </el-form-item>
                </el-form>
                <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible2 = false">取消</el-button>
                    <el-button type="primary" @click="handleEditUser">确定</el-button>
                </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template> 

<script setup>
import { Plus } from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from 'vue'
import Service from "./api/index"
import { ElMessage, ElMessageBox  } from 'element-plus'

    // 添加用户的验证
    const rules = {
        password: [
            { required: true, message: "请输入正确的密码",  trigger: 'blur' },
            { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        username:[
             { required: true, message: "请输入用户名",  trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        nickname:[
             { required: true, message: "请输入用户名",  trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        email: [
            { required: true, message: '请输入注册邮箱', trigger: 'change' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        
    }

    // 修改用户的验证
    const rules2 = {
        password: [
            { required: true, message: "请输入正确的密码",  trigger: 'blur' },
            { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        username:[
             { required: true, message: "请输入用户名",  trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        nickname:[
             { required: true, message: "请输入用户名",  trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        email: [
            { required: true, message: '请输入注册邮箱', trigger: 'change' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        
    }

    const userRules = ref()

    const userRules2 = ref()

    const state = reactive({     
        tableData: [], 

        form:[],

        role: [],

        editList: [],
    })
    
    // 添加用户对话框
    let dialogFormVisible = ref(false)
    // 修改用户对话框
    let dialogFormVisible2 = ref(false)

    onMounted(() => {
        getUserinfo()
    })
    
    // 获取所有用户数据
    const getUserinfo = async() => {
        let res = await Service.getPersonUserinfo()
        console.log(res)
        if(res.code === 200){
            state.tableData = res.data.users
            state.role = res.data.roles
            // console.log(state.tableData)
        }
    }

    // 打开添加用户的对话框
    const handleAddUser = () => {
        dialogFormVisible.value = true
        console.log(state.form)
    }

    // 添加用户发起异步请求
    const handleAdd = async() => {
        console.log(state.form)
        let res = await Service.postPersonUserinfo({...state.form})
        if(res.code === 200){
            ElMessage({
              type: 'success',
              message: res.message
            })
            getUserinfo()
            state.form = []
            dialogFormVisible.value = false
        }else{
             ElMessage({
              type: 'info',
              message: res.message
            })
        }
    }

    // 打开修改用户的对话框
    const handleEdit = (data) => {
        state.editList = data
        dialogFormVisible2.value = true
    }

    // 修改用户发起异步请求
    const handleEditUser = async() => {
        state.editList.roles__id = state.editList.roles__title
        let res = await Service.editPersonUserinfo(state.editList)
        if(res.code === 200){
            ElMessage({
              type: 'success',
              message: res.message
            })
            getUserinfo()
            dialogFormVisible2.value = false
        }else{
             ElMessage({
              type: 'info',
              message: res.message
            })
        }
    }

    // 删除用户
    const handleDelete = (i) => {
        console.log(i)
        ElMessageBox.confirm(
            '确定要删除此用户嘛?',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        .then(async() => {
            let res = await Service.deletePersonUserinfo(i)
            console.log(res)
            if(res.code === 200){
                console.log("Aaaaa")
                ElMessage({ 
                    type: 'success',
                    message: "删除成功",
                })
                console.log("bbbbbb")
                getUserinfo()
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除取消',
            })
        }) 
    }

    // 更改用户状态
    const handleStatus = async(data) => {
        let res = await Service.editPersonUserinfo(data)
        if(res.code === 200){
            ElMessage({
              type: 'success',
              message: "更改成功",
            })
        }else{
            ElMessage({
              type: 'success',
              message: "更改失败",
            })
        }
    }

    // 时间转换
    const timeFormatter = (row, column, cellValue, index) => {
        let format = "YYYY-mm-dd HH:MM:SS"
        let date = new Date(cellValue)
        const dataItem = {
            "Y+": date.getFullYear().toString(),
            "m+": (date.getMonth() + 1).toString(),
            "d+": date.getDate().toString(),
            "H+": date.getHours().toString(),
            "M+": date.getMinutes().toString(),
            "S+": date.getSeconds().toString()
        }
        Object.keys(dataItem).forEach((item) => {
            const ret = new RegExp(`(${item})`).exec(format);
            if(ret){
                format = format.replace(ret[1], ret[1].length === 1? dataItem[item]: dataItem[item].padStart(ret[1].length, "0"))
            }
        });
        return format
    }

</script>

<style scoped>
.header{
    display: flex;
    margin: 15px 0 20px 30px;
}
.tables{ 
    margin: 0 30px;
}
.forms{
    display: flex;
    flex-wrap: wrap;
}
.el-form-item{
    width: 270px;
    display: block;
    text-align: left;
    margin-left: 50px;
}
.signa{
    width: 590px;
}
</style>
